package io.renren.sf.controller;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.SysLog;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Download;
import io.renren.common.utils.PageUtil;
import io.renren.common.utils.RandomUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.sf.entity.CampusEntity;
import io.renren.sf.service.CampusService;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author cyl_txw
 * @email cyl_txw@gmail.com
 * @date 2021-03-18 15:41:54
 */
@RestController
@RequestMapping("sf/campus")
public class CampusController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CampusService campusService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 校区分页
     */
    @GetMapping("/list")
    public R campusPage(@RequestParam Map<String,Object> params){
        Page<CampusEntity> page = campusService.selectCampusEntityPage(params);
        return R.ok().put("campusPage",page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{campusId}")
    //@RequiresPermissions("sf:campus:info")
    public R info(@PathVariable("campusId") Long campusId){
        Map<String, Integer> map = campusService.getCampus(campusId); // 获取省市区code
        Integer regionId = map.get("regionId");
        Integer cityId = map.get("cityId");
        Integer provinceId = map.get("provinceId");
        List<String> ssqList = new ArrayList<>();
        ssqList.add(provinceId.toString());
        ssqList.add(cityId.toString());
        ssqList.add(regionId.toString());
        CampusEntity campus = campusService.getById(campusId);
        campus.setCity(ssqList);
        return R.ok().put("campus", campus);
    }

    /**
     * 保存
     */
    @SysLog("新建校区")
    @PostMapping("/save")
    //@RequiresPermissions("sf:campus:save")
    public R save(@RequestBody CampusEntity campus) {
        Integer cid = null;
        try {
            // 首先像省市区表中添加数据
            cid = campusService.insertssq(campus.getCity());
        } catch (RRException e) {
            return R.error(e.getMessage());
        }
        campus.setCid(cid);
        campus.setCreateTime(new Date());
        // 新建校区时，总人数为0
        campus.setNum(0);
        campusService.save(campus);
        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改校区信息")
    @PostMapping("/update")
    //@RequiresPermissions("sf:campus:update")
    public R update(@RequestBody CampusEntity campus){
        Integer cid;
        try {
            // 首先像省市区表中添加数据
            cid = campusService.insertssq(campus.getCity());
        } catch (RRException e) {
            return R.error(e.getMessage());
        }
        campus.setCid(cid);
		campusService.updateById(campus);
        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除校区")
    @PostMapping("/delete")
    //@RequiresPermissions("sf:campus:delete")
    public R delete(@RequestBody Long[] campusIds){
		campusService.removeByIds(Arrays.asList(campusIds));
        return R.ok();
    }

    /**
     * 获取所有未分配的校区负责人
     * @return
     */
    @GetMapping("/getXqfzr")
    public R getXqfzr(){
        // 获取以分配的user_id
        /*List<CampusEntity> list = campusService.list();
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        if(!CollectionUtils.isEmpty(list)){
            for (CampusEntity campusEntity : list) {
                queryWrapper.ne("user_id",campusEntity.getUserId());
            }
        }*/
        List<SysUserEntity> sysUserEntities = sysUserService.list(null);
        return R.ok().put("xqfzrList",sysUserEntities);
    }
    /**
     * 获取所有校区
     */
    @GetMapping("/getCampusList")
    public R getCampusList(){
        List<CampusEntity> list = campusService.list();
        return R.ok().put("campusList",list);
    }

    /**
     * 批量新增cdk
     */
    @SysLog("批量新增激活码")
    @GetMapping("/saveBatchCdk")
    public R saveBatchCdk(@RequestParam("campusId") Long campusId, @RequestParam("num") Integer num){
        BoundHashOperations<String,String,String> ops = redisTemplate.boundHashOps("cdk");
        for (int i = 0; i < num; i++) {
            // 8位激活码
            String cdk = RandomUtils.randomUtil();
            ops.put(cdk, campusId.toString());
        }
        return R.ok();
    }
    /**
     * 获取cdk列表
     */
    @GetMapping("/getCdkList")
    public R getCdkList(@RequestParam Map<String, Object> params){
        String campusId1 = (String) params.get("campusId");
        int page = Integer.parseInt((String) params.get("page"));
        int limit = Integer.parseInt((String) params.get("limit"));
        BoundHashOperations<String,String,String> ops = redisTemplate.boundHashOps("cdk");
        Map<String, String> cdkAndCampusIdMap = ops.entries();
        if(CollectionUtils.isEmpty(cdkAndCampusIdMap)){
            return R.error("没有cdk");
        }
        List<Map<String, String>> list = new ArrayList<>();
        Set<String> cdkSet = ops.entries().keySet();

        for (String cdk : cdkSet) {
            String campusId = cdkAndCampusIdMap.get(cdk);
            if(!StringUtils.isEmpty(campusId1)){
                if(!campusId1.equals(campusId)){
                    continue;
                }
            }
            Map<String, String> cdkAndCampusId = new HashMap<>();
            cdkAndCampusId.put("cdk", cdk);
            cdkAndCampusId.put("campusId", campusId);
            list.add(cdkAndCampusId);
        }
        PageUtil<Map<String, String>> cdkPage = new PageUtil<>(page, limit, list);
        return R.ok().put("cdkPage", cdkPage);
    }

    /**
     * 删除
     */
    @SysLog("删除激活码")
    @PostMapping("/deleteCdk")
    //@RequiresPermissions("sf:campus:delete")
    public R deleteCdk(@RequestBody String[] cdks){
        BoundHashOperations<String,String,String> ops = redisTemplate.boundHashOps("cdk");
        ops.delete(cdks);
        return R.ok();
    }
}
